let express = require("express");
const valid = require("../classes/validate.js");
const user = require("../classes/user.js");
// const md5 = require('md5');
let bodyParser = require("body-parser");
// let sessionWrap = require("../classes/session.js");
let cryptor = require("../classes/crypto.js");
let tokenManager = require("../classes/token.js");

//处理过程工具
const proc = require("../classes/process.js");

//rsa加密工具
let cryptoManager = cryptor();

let api = express.Router();
let validate = new valid();
// let user = new userdb();
// create application/json parser
var jsonParser = bodyParser.json();

//session 控制对象
// let sessionObj = new sessionWrap();
 
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

//生成set-cookie值
// let serialize = function( name , val , opt ){
//     let pairs = [ name + '=' + encodeURI(val) ];
//     opt = opt || {};

//     if( opt.maxAge ) pairs.push("Max-Age=" + opt.maxAge);
//     if( opt.domain ) pairs.push("Domain=" + opt.domain);
//     if( opt.path ) pairs.push("Path=" + opt.path);
//     if( opt.expires ) pairs.push("Expires=" + opt.expires.toUTCString());
//     // if( opt.httpOnly ) pairs.push("HttpOnly");
//     // if( opt.secure ) pairs.push("Secure");

//     return pairs.join("; ");
// }
//使用session 用在路由器上
// api.use(sessionObj.config());

//注册
api.post("/regist_account" ,jsonParser,  async function(req , res , next ){
   
    //检查申请注册的参数
    let params = req.body;
    // 检验邮箱是否含有空白字符
    if( validate.checkEmailWithEmptyFlag( params.account ) ){
        next({
            status: 400,
            code: 400005,
            msg:"邮箱内含有空白字符,请重新输入"
        });
        return ;
    }
    //校验邮箱格式
    if( !validate.checkEmail( params.account ) ){
        
        //错误
        next({
            status: 400,
            code: 400002,
            msg: "注册邮箱格式不正确"
        });
        return ;
    }

    //检查密码是否含有空白字符
    if( validate.checkpasswordWithEmptyFlag( params.password ) ){
        next({
            status: 400,
            code: 400006,
            msg: "密码不能含有空白字符，请重新输入"
        });
    }

    
    if( !validate.checkPasswordEmpty( params.password ) ){
        //密码为空字符串
        next({
            status: 400,
            code: 400003,
            msg: "注册密码格式不正确"
        });
        return ;
    }

    //校验帐号是否已存在，不允许重复注册
    try{
        let isExist = await user.checkUserExist(params.account);
        
        if( isExist.length != 0 ){
            //用户已经存在
            next({
                status: 400,
                code: 400004,
                msg: "用户已存在, 请换一个邮箱注册"
            });
            return ;
        }

        //加密用户密码


        //记录新用户
        let addNewUser = await user.registNewUserByEmail( params.account , params.password );
        
        if( addNewUser.affectedRows == 0 ){
            next({
                status: 500,
                code: 500001,
                msg: "服务器内部错误,注册失败,请稍后尝试。"
            });
            return ;
        }
        
        // req.session.accountID =  addNewUser.insertId;
        // req.session.cookie.maxAge = 2 * 60 * 1000;
        
        res.statusCode = 200;
        res.send( JSON.stringify({
        	code: 0,
        	msg: "注册成功"
        }));
        res.end();

    }catch(err){
        console.log(err);
        next(err);
    }

	
});

//登录请求处理
api.post("/login",jsonParser, function(req ,res , next){
   
    let params = req.body;
    
    //检查邮箱名是否含有空白字符
    if( validate.checkEmailWithEmptyFlag( params.account ) ){
        next({
            status: 400,
            code: 400005,
            msg:"邮箱含有空白字符，请重新输入"
        });
        return ;
    }

    //检查帐号名是否是邮箱
    if( !validate.checkEmail( params.account ) ){
        
        next({
            status: 400,
            code: 400002,
            msg: "邮箱格式不正确"
        });
        return ;
    }
    //检查密码是否含有空白字符
    if( validate.checkpasswordWithEmptyFlag( params.password )){

        next({
            status: 400,
            code: 400006,
            msg:"密码不能含有空白字符"
        });
        return ;
    }
    //检查密码是否是空字符串
    if( !validate.checkPasswordEmpty( params.password ) ){
        next({
            status: 400,
            code: 400003,
            msg: "密码格式错误，请重新输入"
        });
        return ;
    }
    //检查cookies
    
    // res.setHeader("Set-Cookie", serialize("isvisit", 2,{
    //     path: "/",
    //     // domain:"localhost:8080",
    //     // expires: new Date(2020,11,1)
    // }) );
    // res.setHeader("Content-Type", "application/json;charset=utf-8")
    
    //检查用户是否存在
    user.loginAccountByPassword( params.account ).then( async ires=>{
        
        //设置session

        // console.log("session: ", req.cookie );
        // req.sessionStore.get(req.cookie['connect.sid'], function(res){
        //     console.log("get session: ", res);
        // });
        // console.log("session store: ", sessionObj.dbStore());

        console.log("user ires: ", ires);
        if(ires.length === 0){
            next({
                status: 400,
                code: 400015,
                msg:"此帐号不存在"
            });
            return;
        }

        let loginPsw = cryptoManager.decryptContent( params.password ).plaintext;
        let userPsw = cryptoManager.decryptContent( ires[0].cus_passphrase ).plaintext;
        if(  ires.length == 0 ){
            next({
                status: 400,
                code: 400007,
                msg: "登录失败"
            });
            return ;
        }
        if( loginPsw == userPsw ){
            //改变用户登录状态
            let userStatusChange = await user.changeUserStatus({
                // id : 0,
                userId: ires[0].cus_id,
                status: 0,  //登录状态： 在线
                time: new Date()
            });
            
            
            if( userStatusChange.Error ){
                next({
                    status: 500,
                    code: 500001,
                    msg: "服务器忙" 
                });
                //需要记录到错误日志
                return ;
            }

            //生成token
            let token = tokenManager.generateToken({user_id: ires[0].cus_id});
            

            res.statusCode = 200;
            res.send(JSON.stringify({
                code: 0,
                data:{
                    token: token
                },
                msg: "登录成功"
            }));
            res.end();
        }else{
            next({
                status: 400,
                code: 400014,
                msg: "错误密码"
            });
            return ;
        }
        
    }).catch(err=>{
        console.log("登录错误： ", err);
        next({
            status: 500,
            code: 500001,
            msg: "服务器忙,请稍后再试" 
        });
        return ;
    });
    
    
});

//查看用户在线状态（未完成）
api.get("/userstatus" , function( req , res , next){
    
    let enToken = req.headers.token;
    
    res.statusCode = 200;
    res.send( JSON.stringify({
        code: 0,
        data:{
            status: 0 //0:在线 1:离线
         }
    }) );
    res.end();
});

//用户信息
api.get("/userInfo", function( req , res , next ){
    
    const token = req.headers.token;
    proc.auth_check( token , function( user_id ){
        user.getUserInformation( user_id ).then(
            infoRes =>{
                
                let buffer = infoRes[1][0].headerImg
                let base64Str = buffer ?  buffer.toString('utf8') : null;
                
                let { ...infoData } = infoRes[1][0];
                infoData.headerImg = base64Str ? JSON.parse(base64Str).avatar : null;//头像数据转码
                
                res.statusCode = 200;
                res.send(JSON.stringify({
                    code: 0,
                    data: infoData
                }));
                res.end();
            }
        ).catch(
            infoError=>{
                console.log("用户信息err:", infoError);
                next({
                    status: 500,
                    code: 500001,
                    msg: "服务器内部错误"
                });
            }
        );
    }, next );
});

//设置用户头像
api.post("/setAvatar", jsonParser , function(req , res , next){
    
    let avatarData = req.body;
    let token = req.headers.token;
    proc.auth_check( token , function( user_id ){
        user.setUserAvatar( user_id , avatarData ).then(uAvatarRes=>{
            console.log("头像设置： ", uAvatarRes );
            if( uAvatarRes.affectedRows == 1 ){
                res.statusCode = 200;
                res.send( JSON.stringify({
                    code: 0,
                    msg:"头像更新成功"
                }) );
                res.end();
                return ;
            }
            next({
                status: 500,
                code: 500001,
                msg: "内部错误"
            });

        }).catch(uAvatarErr=>{
            //头像设置错误
        });
    }, next);

});

//设置用户昵称
api.post("/setNickName", jsonParser , function( req , res , next ){
    let nick_name = req.body.nickName;
    
    let token = req.headers.token;
    proc.auth_check( token , function( user_id ){
        user.setUserNickName( user_id , nick_name ).then(
            nickNameRes =>{
                console.log("昵称设置结果：", nickNameRes);
                if( nickNameRes.affectedRows == 1 ){
                    res.statusCode = 200;
                    res.send( JSON.stringify({
                        code: 0,
                        msg:"昵称更新成功"
                    }) );
                    res.end();
                    return ;
                }

                next({
                    status: 500,
                    code: 500,
                    msg: "内部错误"
                });
            }
        ).catch( nickNameError =>{
            //昵称设置错误

        });
    }, next);
});

//修改密码
api.post("/changePwd", jsonParser ,  function( req , res , next ){
    let pwdContent = req.body;
    let token = req.headers.token;

    proc.auth_check( token , async function( user_id ){
        //取出用户密码
        let user_pwd = await user.getUserPwd( user_id );
        user_pwd = cryptoManager.decryptContent( user_pwd[0].pwd ).plaintext ;
        let origin_pwd = cryptoManager.decryptContent( pwdContent.cur_pwd ).plaintext ;
        if( user_pwd == origin_pwd ){
            //判断原始密码是否相等
            
            user.changeUserPwd( user_id , pwdContent.new_pwd ).then( changePwdRes=>{
                console.log("修改密码： ", changePwdRes );
                if( changePwdRes.affectedRows == 1 ){
                    res.statusCode = 200;
                    res.send(JSON.stringify({
                        code: 0,
                        msg:"密码修改成功"
                    }));
                    res.end();
                    return ;
                }
                next({
                    status: 500,
                    code: 500001,
                    msg: "内部错误"
                });
                
            } ).catch(changePwdErr=>{
                //密码修改错误 （未完成）
            });
            return ;
        }
        res.statusCode = 200;
        res.send(JSON.stringify({
            code: 0,
            msg:"当前密码不对，请重试"
        }));
        res.end();
        
        return ;
    }, next);

});

//安全退出
api.get("/logOut", function( req , res , next){
    let token = req.headers.token;
    
    proc.auth_check( token , function( user_id ){
        user.saftyLogout( user_id ).then( 
            logoutRes =>{
                
                if( logoutRes.affectedRows == 1 ){
                    res.statusCode = 200;
                    res.send(JSON.stringify({
                        code: 0,
                        msg:"安全退出"
                    }));
                    res.end();
                    return ;
                }
                next({
                    status: 500,
                    code: 500001,
                    msg: "内部错误"
                });
                return ;
            }
         ).catch(
             logoutErr=>{
                next({
                    status: 500,
                    code: 500001,
                    msg: "服务器忙"
                });
                return ;
             }
         );
    }, next);
});

//错误处理
api.use(function( err , req , res , next){
    
    if( err ){

        res.statusCode= err.status;
        res.send( JSON.stringify({
            code: err.code,
            msg: err.msg
        }) );
        res.end();
    }else{
        next();
    }
    
});



module.exports = api;